
package threadlogging.log4j;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.log4j.NDC;


/**
 * 
 * servlet filter
 * 
 * @author Sean C. Sullivan
 *
 */
public class LoggingServletFilter
	implements Filter
{
	private static Logger logger = Logger.getLogger(LoggingServletFilter.class);
	
	public void doFilter(ServletRequest req, ServletResponse rsp,
			FilterChain chain) throws IOException, ServletException
	{
		
		long startTime = System.currentTimeMillis();
		
		try
		{
			clear();
			
			ThreadTrace.setEnabled(true);
			ThreadTrace.setHttpRequest( (HttpServletRequest) req);

			chain.doFilter(req, rsp);
		}
		finally
		{
			
			long endTime = System.currentTimeMillis();
			
			long requestTime = endTime - startTime;
			
			logger.info("Request processing time: " + (requestTime / 1000.0) + " seconds");
			
			try
			{
				if (ThreadTrace.hasError())
				{
					SMTPAppender.sendEmail();
				}
			}
			finally
			{
				clear();
			}
		}
	}

	
	protected void clear()
	{
		try
		{
			NDC.clear();
			Log4jUtil.clearMDC();
		}
		finally
		{
			try
			{
				ThreadTrace.clear();
			}
			finally
			{
				ThreadTrace.setEnabled(false);
			}
		}
	}
	
	public void init(FilterConfig config) throws ServletException
	{
		// empty
	}

	public void destroy()
	{
		// empty method
	}

}
